﻿import win32api
import win32con
import win32gui
import time
import win32clipboard as w
import os


def FindWindow(chatroom,flag=True):
    win = win32gui.FindWindow(None, chatroom)
    print("找到群聊窗口：%x" % win)
    if win != 0:
        if flag:
            win32gui.ShowWindow(win, win32con.SW_SHOWMINIMIZED)
            win32gui.ShowWindow(win, win32con.SW_SHOWNORMAL)
            win32gui.ShowWindow(win, win32con.SW_SHOW)
            win32gui.SetWindowPos(win, win32con.HWND_TOPMOST, 100, 100, 300, 300, win32con.SWP_SHOWWINDOW)
            win32gui.SetForegroundWindow(win)  # 获取控制
        time.sleep(1)
        return win
    else:
        print('请注意：找不到【%s】这个人（或群），请激活窗口！' % chatroom)
        return False
        #exit()


def CloseWindow(chatroom):
    win = win32gui.FindWindow(None, chatroom)
    # print("找到关闭窗口：%x" % win)
    time.sleep(3)
    win32gui.ShowWindow(win, win32con.SW_SHOWMINIMIZED)


def setText(aString):
    w.OpenClipboard()
    w.EmptyClipboard()
    w.SetClipboardData(win32con.CF_UNICODETEXT, aString)
    w.CloseClipboard()


def ctrlV():
    win32api.keybd_event(17, 0, 0, 0)  # ctrl键位码是17
    win32api.keybd_event(86, 0, 0, 0)  # v键位码是86
    win32api.keybd_event(86, 0, win32con.KEYEVENTF_KEYUP, 0)  # 释放按键
    win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)


def altS():
    win32api.keybd_event(18, 0, 0, 0)  # Alt键位码
    win32api.keybd_event(83, 0, 0, 0)  # s键位码
    win32api.keybd_event(18, 0, win32con.KEYEVENTF_KEYUP, 0)  # 释放按键
    win32api.keybd_event(83, 0, win32con.KEYEVENTF_KEYUP, 0)


def sendText(chatroom, text):
    FindWindow(chatroom)
    # 文字首行留空，防止带表情复制不完全
    setText(" " + text)
    time.sleep(1)
    ctrlV()
    time.sleep(1)
    altS()
    CloseWindow(chatroom)


def sendImg(chatroom):
    FindWindow(chatroom)
    time.sleep(1)
    ctrlV()
    time.sleep(1)
    altS()
    CloseWindow(chatroom)



def ExitWindow(chatroom):
    try:
        win = win32gui.FindWindow(None, chatroom)
        print("找到关闭窗口：%x" % win)
        time.sleep(3)
        win32gui.CloseWindow(win)
    except:
        print('找不到窗口！！！')


def kill_pocess(program="Touchvew.exe"):
    print("正在关闭组态王！")
    os.system("taskkill /F /IM {0}".format(program))

def start_pocess(path=r"C:\Program Files (x86)\kingview\TouchVEW.exe"):
    win32api.ShellExecute(0, 'open', path, '', '', 1)

def setImage(data):
    w.OpenClipboard()  # 打开剪贴板
    w.EmptyClipboard()  # 先清空剪贴板
    w.SetClipboardData(win32con.CF_DIB, data)  # 将图片放入剪贴板
    w.CloseClipboard()


    #win32gui.PostMessage(win, win32con.WM_CLOSE, 0, 0)
    #win32gui.ShowWindow(win, win32con.SW_SHOWMINIMIZED)

if __name__ == '__main__':
    if FindWindow("运行系统",False):
        print("组态王运行系统")
    elif FindWindow("CELL监控系统运行中...", False):
        print("组态王CELL运行系统")